<?php

namespace Henan\ThinkSdk\utils;

/**
 * 加密工具
 */
class EncryptUtil
{
    /**
     * AES对称加密算法-加密
     * @param string $text 明文
     * @param string $key 密钥
     * @return string
     */
    public static function AES_Encrypt(string $text, string $key): string
    {
        $iv = openssl_random_pseudo_bytes(16);
        $encrypted = openssl_encrypt($text, 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv);
        return base64_encode($iv . $encrypted);
    }

    /**
     * AES对称加密算法-解密
     * @param string $text 密文
     * @param string $key 密钥
     * @return false|string
     */
    public static function AES_Decrypt(string $text, string $key): false|string
    {
        $encryptedData = base64_decode($text);
        $iv = substr($encryptedData, 0, 16);
        $text = substr($encryptedData, 16);
        return openssl_decrypt($text, 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv);
    }
}